﻿miniSched.entityModel = function (params) {
    var self = this;
    var params = params || {};

    self.Id = ko.observable(params.Id);
    self.Timestamp = ko.observable(params.Timestamp);
    self.apiError = ko.observable();
    self.isPersisted = ko.observable(!!self.Id());

    for (var property in self) {
        if (property && self[property] && self[property].subscribe && (property != "isPersisted")) {
            self[property].subscribe(function () {
                self.isPersisted(false);
            });
        }
    }
};

miniSched.entityModel.extend(miniSched.model);

miniSched.entityModel.prototype.save = function (settings) {
    var self = this;

    var settings = $.extend(true, settings, {
        data: self.toJson()
    });

    var method = function (settings) {
        return self.Id()
            ? self.apiClient.put(settings)
            : self.apiClient.post(settings);
    };

    return method(settings)
        .done(function (data, textStatus, jqXHR) {
            self.Id(data.Id);
            self.Timestamp(data.Timestamp);
            self.apiError("");
            self.isPersisted(true);
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            self.apiError("An error occurred."); // TODO: Get the error description.
            self.isPersisted(false);
        });
};
